package admin

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductSaveLogic {
	return &ProductSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductSaveLogic) ProductSave(req *types.ProductSaveReq) (resp string, err error) {
	if !utils.GetDataById(req.CategoryID, &models.Category{}) {
		return "", errors.New("商品类目不存在")
	}

	data := &models.Product{
		Name:         req.Name,
		CategoryID:   req.CategoryID,
		MainImage:    req.MainImage,
		Description:  req.Description,
		DetailHTML:   req.DetailHTML,
		IsOnSale:     req.IsOnSale,
		ImageGallery: req.ImageGallery,
	}

	if req.Id == 0 {
		// 创建新角色
		err = utils.InsertData(data)
	} else {
		err = utils.UpdateById(req.Id, data)
	}

	if err != nil {
		logx.Errorf("操作商品失败: %v", err)
		return "", err
	}

	return "操作成功", nil
}
